<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from "vue";
import api from "@/api/blog/blog";
import apiRead from "@/api/blog/read";
import { useRoute, useRouter } from "vue-router";
import pubsub from "pubsub-js";
import Comment from "@/components/comment.vue";
import Scroll from "@/components/plugs/scroll.vue";
import { getOptNameType } from "@/utils/utils";

const route = useRoute();
let model: any = reactive({});
let preview: any = ref(null);
let router = useRouter();

onMounted(async () => {
    readBlog()
    const res = await api.getmodel({ _id: route.query.id });
    Object.assign(model, res.data);
    nextTick(() => {
        const anchors = preview.value.$el.querySelectorAll("h1,h2,h3,h4,h5,h6");
        const anchorsArr: any = Array.from(anchors).filter((title: any) => !!title.innerText.trim());
        const hTags = Array.from(new Set(anchorsArr.map((title: any) => title.tagName))).sort();
        let directory = reactive({});
        directory = anchorsArr.map((el: any) => ({
            title: el.innerText,
            lineIndex: el.getAttribute("data-v-md-line"),
            indent: hTags.indexOf(el.tagName),
            el,
        }));
        pubsub.publish("directory", directory);
    });
});

const readBlog = () => {
    api.readBlog({ _id: route.query.id }).then((res) => {
    })

    apiRead.update({ path: router.currentRoute.value.name });
}

</script>

<template>
    <div class="read-warp">
        <div class="read-title">{{ model.title }}</div>
        <div class="read-tip">
            <el-tag type="danger" style="margin-right: 10px">{{ getOptNameType("blog_type", model.type) }}</el-tag>
            <el-tag type="warning"> {{ model.createTime }}</el-tag>
        </div>
        <el-divider> 简 述 </el-divider>
        <div class="read-desc">{{ model.desc }}</div>
        <el-divider> 正 文 </el-divider>
        <v-md-preview :text="model.mdContent" ref="preview"></v-md-preview>

        <Comment :blog_id="route.query.id"></Comment>
        <Scroll />
    </div>
</template>

<style lang="scss" scoped>
.read-warp {
    background-color: var(--c-bg-box);
    border-radius: 10px;
    padding-top: 20px;
    padding-bottom: 100px;

    border: 1px solid #E6E8EB;

    .read-title {
        font-size: 28px;
        font-weight: 700;
        color: var(--el-color-primary);
        text-align: center;
        margin-bottom: 10px;
    }

    .read-tip {
        display: flex;
        justify-content: center;
    }

    .read-cover {
        width: 100%;
        height: 400px;
        object-fit: cover;
        margin: 20px 0;
        border-radius: 5px;
    }

    .read-desc {
        color: var(--c-text-2);
        padding: 10px 40px;
    }
}
</style>
